package com.uchonor.api.core.service;

import com.uchonor.olight.agent.annotation.Inject;
import com.uchonor.olight.agent.annotation.Service;
import com.uchonor.olight.agent.utils.AssertUtils;
import org.ssssssss.magicapi.core.config.MagicConfiguration;
import org.ssssssss.magicapi.core.model.Group;
import org.ssssssss.magicapi.core.model.JsonBean;
import org.ssssssss.magicapi.core.model.MagicEntity;
import org.ssssssss.magicapi.core.resource.FileResource;
import org.ssssssss.magicapi.core.resource.Resource;
import org.ssssssss.magicapi.core.service.MagicResourceService;

import java.util.Objects;

@Service
public class ResourceService {
    @Inject
    private MagicResourceService service;

    /**
     * 保存资源
     * @param entity
     */
    public void saveFolder(MagicEntity entity){
        // 自动保存的代码，和旧版代码对比，如果一致，则不保存，直接返回。
        if(entity.getId() != null){
            MagicEntity oldInfo = service.file(entity.getId());
            if(oldInfo != null && Objects.equals(oldInfo, entity)){
                return;
            }
        }
        if (MagicConfiguration.getMagicResourceService().saveFile(entity)) {
            return;
        }
        throw new RuntimeException("保存错误！");
    }



    public void delete(String id) {
        Group group = service.getGroup(id);
        if(group == null){
            MagicEntity entity = service.file(id);
            AssertUtils.notNull(entity,"删除失败，对应资源找不到");
        }
        if(!service.delete(id)){
            throw new RuntimeException("删除失败！");
        }
    }

    public void saveGroup(Group group){
        Resource resource = service.getResource();
        if(resource instanceof FileResource){
            if(!resource.exists()){
                throw new RuntimeException("配置的文件路径不存在，请检查！");
            }
        }
        if (service.saveGroup(group)) {
            return;
        }else {
            throw new RuntimeException("保存失败！");
        }

    }
}
